const { execSync } = require('child_process')
const path = require('path')
const fs = require('fs')

const packagesDir = path.join(process.cwd(), 'packages')

const packages = fs
  .readdirSync(packagesDir, { withFileTypes: true })
  .filter(dirent => dirent.isDirectory())
  .filter(dirent =>
    fs.existsSync(path.join(packagesDir, dirent.name, 'package.json'))
  )
  .filter(dirent => {
    const result = JSON.parse(
      fs.readFileSync(path.join(packagesDir, dirent.name, 'package.json'))
    ).scripts
    return result ? Reflect.has(result, 'release') : false
  })
  .map(dirent => dirent.name)

if (packages.length === 0) {
  console.log('No packages found in packages directory')
  process.exit(0)
}

console.log('Select a package to release:\n')
packages.forEach((pkg, index) => {
  console.log(`${index + 1}. ${pkg}`)
})

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})

readline.question(`Enter package number (1-${packages.length}): `, answer => {
  readline.close()

  const index = parseInt(answer) - 1
  if (isNaN(index) || index < 0 || index >= packages.length) {
    console.error('\nInvalid package number')
    process.exit(1)
  }

  const packageDir = path.join(packagesDir, packages[index])

  console.log(`\nReleasing ${packages[index]}...`)

  try {
    execSync('pnpm release', { cwd: packageDir, stdio: 'inherit' })
  } catch {
    return
  }
})
